package com.itheima.reggie.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author ：sean
 * @date ：Created in 2022/5/19
 * @description ：
 * @version: 1.0
 */
@Slf4j
@Component
	public class MyMetaObjectHandler implements MetaObjectHandler {
	@Override
	public void insertFill(MetaObject metaObject) {
		// metaObject当前被填充的对象
		// 自动填充填充的实体类，是在写数据库之前
		Thread thread = Thread.currentThread();
		log.info("[公共自动填充,插入数据]:当前线程ID:{}",thread.getId());
		log.info("[公共自动填充,插入数据],{}",metaObject.toString());
		metaObject.setValue("createTime", LocalDateTime.now());
		metaObject.setValue("updateTime", LocalDateTime.now());
		// MyMetaObjectHandler这个独立对象，无法接受request对象的
		// User如何填充，获取的当前登录用户的ID，从session获取
		// session如何获取的？request.getSession
		// 现在无法解决，默认先写1，管理员ID
		Long currentId = BaseContext.getCurrentId();
		metaObject.setValue("createUser",currentId);
		metaObject.setValue("updateUser",currentId);
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		Thread thread = Thread.currentThread();
		log.info("[公共自动填充,更新数据]:当前线程ID:{}",thread.getId());
		log.info("[公共自动填充,更新数据],{}",metaObject.toString());
		metaObject.setValue("updateTime", LocalDateTime.now());
		Long currentId = BaseContext.getCurrentId();
		metaObject.setValue("updateUser",currentId);
	}
}
